﻿using NetFrame.EnDecode;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Text;

namespace NetFrame.Base
{
    [Serializable]
    [ProtoContract]
    public class TransModel
    {
        [ProtoMember(1)]
        public byte type;
        [ProtoMember(2)]
        public int area;
        [ProtoMember(3)]
        public int command;
        
        [NonSerialized]
        [ProtoMember(4)]
        public byte[] msgProbuf;
        
        [ProtoIgnore]
        public string msgJson;

        public TransModel() { }

        public TransModel(byte t, int a, int c) {
            type = t;
            area = a;
            command = c;
        }

        public void SetMsg<T>(T msg,MsgType type=MsgType.Protobuf) {
            try {
                switch (type) {
                    case MsgType.Protobuf:
                        msgProbuf= SeProtobuf.Serialization(msg);
                        break;
                    case MsgType.Json:
                        msgJson = SeJson.Serialization(msg);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }

        public T GetMsg<T>() {
            try {
                if (msgProbuf != null && msgProbuf.Length > 0) {
                    return SeProtobuf.DeSerialization<T>(msgProbuf);
                }
                else if (msgJson != null && msgJson != string.Empty) {
                    return SeJson.DeSerialization<T>(msgJson);
                }
                else {
                    return default(T);
                }
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                return default(T);
            }
            
        }
    }

    public enum MsgType {
        Protobuf,
        Json
    }
}
